import request from '@/utils/request'
import type { Shot } from '@/types'

// 定义基础响应类型
export interface BaseResponse {
  success: boolean
  error?: string
}

// 定义导出相关的类型
export interface ExportParams {
  folderName: string
  shots: Shot[]
}

// 导出服务API
export const exportApi = {
  /**
   * 导出选中的分镜图片
   */
  async exportImages(folderName: string, shots: Shot[]): Promise<void> {
    try {
      // 确保所有分镜都有图片数据
      const validShots = shots.filter(shot => shot.image)
      if (validShots.length === 0) {
        throw new Error('没有可导出的图片数据')
      }

      const response = await request.post('/export/images', {
        folderName,
        shots: validShots.map(shot => ({
          id: shot.id || 0,
          originalText: shot.originalText,
          image: shot.image
        }))
      }, {
        responseType: 'blob'
      })

      // 创建并触发下载
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `${folderName}.zip`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error('导出图片失败:', error)
      throw new Error(error instanceof Error ? error.message : '导出图片失败')
    }
  },

  /**
   * 导出分镜为视频
   */
  async exportVideo(folderName: string, shots: any[]) {
    try {
      const response = await request.post('/export/video', {
        folderName,
        shots: shots.map(shot => ({
          id: shot.id || 0,
          originalText: shot.originalText,
          image: shot.image,
          audio: shot.audio
        }))
      }, {
        responseType: 'blob'
      })
      // 创建并触发下载
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `${folderName}.mp4`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      return { success: true }
    } catch (error) {
      console.error('导出视频失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '导出视频失败'
      }
    }
  }
}
